package com.java.web.manageweb.controller.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.base.pojo.ItemCatResult;
import com.java.manage.pojo.TbItemCat;
import com.java.manage.service.TbItemCatService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName ApiItemCatController
 * @Description 类目查询API
 * @Author Trigger Wu
 * @Date 2018/9/1315:05
 * @Version 1.0
 **/
@RequestMapping(value = "/rest/api/item/cat" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@Controller
public class ApiItemCatController {
    @Autowired
    private TbItemCatService itemCatService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

//    @RequestMapping(method = RequestMethod.GET)
//    public ResponseEntity<String> queryItemCatList(HttpServletRequest request) {
//
//        String callback = request.getParameter("callback");
//
//        try {
//            ItemCatResult itemCatResult = this.itemCatService.queryAllToTree();
//            String json = MAPPER.writeValueAsString(itemCatResult);
//            if(StringUtils.isEmpty(callback)){
//                return ResponseEntity.ok(json);
//            }
//            return ResponseEntity.ok(callback+"("+itemCatResult+");");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
//    }

        @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<String> queryItemCatList(
            @RequestParam(value = "callback", required = false) String callback) {
        try {
            ItemCatResult itemCatResult = itemCatService.queryAllToTree();
            String json = MAPPER.writeValueAsString(itemCatResult);
            if (StringUtils.isEmpty(callback)) {
                return ResponseEntity.ok(json);
            }
            return ResponseEntity.ok(callback + "(" + json + ");");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}
